/*
 * Giffel, Android application
 *
 * Copyright (C) 2011  Mid Sweden University
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package se.appening;

import java.util.ArrayList;
import java.util.List;

public class SubjectEvent {

    private String subjectTag;
    private List<Listener> listeners = new ArrayList<Listener>();
    
    private final class SignalRunner implements Runnable {
        private Listener listener;
        private EventArg event;

        public SignalRunner(Listener listener, EventArg event) {
            this.listener = listener;
            this.event = event;
        }

        public void run() {
            listener.invoke(subjectTag, event);
        }
    }

    public interface EventArg {
    }
    
    public interface Listener {
        void invoke(String subjectTag, EventArg event);
    }
    
    public SubjectEvent(String subjectTag) {
        this.subjectTag = subjectTag;
    }
    
    public void add(Listener listener) {
        listeners.add(listener);
    }
    
    public void remove(Listener listener) {
        listeners.remove(listener);
    }
    
    public void clear() {
        listeners.clear();
    }
    
    public void signal(EventArg event) {
    	for (Listener listener : listeners) {
    		listener.invoke(subjectTag, event);
    	}
    }
    
    public void signalIndependent(final EventArg event) {
        for (Listener listener : listeners) {
        	Thread th = new Thread(new SignalRunner(listener, event));
        	th.start();
        }
    }
}